package com.example.controller;

import com.example.entity.MyResponseEntity;
import com.example.entity.Role;
import com.example.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author fyxw
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    private final RoleService service;

    public RoleController(RoleService service) {
        this.service = service;
    }

    @PostMapping
    public MyResponseEntity<?> addRole(@RequestBody Role role) {
        service.addRole(role);
        return new MyResponseEntity<>(200, "添加成功", role);
    }

    @DeleteMapping("/{id}")
    public MyResponseEntity<?> deleteRole(@PathVariable int id) {
        if (service.deleteRole(id)) {
            return new MyResponseEntity<>(200, "删除成功", null);
        }
        return new MyResponseEntity<>(404, "删除失败, 无该Role", null);
    }

    @PutMapping
    public MyResponseEntity<?> updateRole(@RequestBody @Valid Role role) {
        // 若role对象id为空，会产生空指针异常，已使用全局异常捕捉该异常，无需手动处理
        if (service.updateRole(role)) {
            return new MyResponseEntity<>(200, "修改成功", null);
        }
        return new MyResponseEntity<>(404, "修改失败", null);
    }

    @GetMapping("/{id}")
    public MyResponseEntity<?> findRole(@PathVariable int id) {
        final Role role = service.findRoleById(id);
        return new MyResponseEntity<>(200, "查询成功", role);
    }

    @GetMapping("/{startPage}/{pageSize}")
    public MyResponseEntity<?> findAllRes(@PathVariable("startPage") int startPage, @PathVariable("pageSize") int pageSize){
        PageHelper.startPage(startPage, pageSize);
        List<Role> roles = service.findAll();
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return new MyResponseEntity<>(200,"查询成功",pageInfo);
    }
}
